package ubc.cs.cpsc210.sustainabilityapp.webservices;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import ubc.cs.cpsc210.sustainabilityapp.model.FoodService;
import ubc.cs.cpsc210.sustainabilityapp.model.*;

/**
 * Parse the output of the search for food service locations in Yelp
 */

public class YelpParser {

	/**
	 * Parse the output of the search for food service locations on Yelp
	 * 
	 * @param json
	 *            The search results as a string (JSON output)
	 * @return A list of food service locations that may be empty but is not
	 *         null
	 */
	public static List<FoodService> parse(String json) {
		
		List<FoodService> foodServices = new ArrayList<FoodService>();
		FoodService tempFoodService;
		
		try {
			
			JSONObject anObject = new JSONObject(json);
			
			JSONArray anArray = anObject.getJSONArray("businesses");
			
			for (int i = 0; i < anArray.length(); i++) {
				
				JSONObject currentRestaurant = anArray.getJSONObject(i);
				JSONObject coordinates = currentRestaurant.getJSONObject("location").getJSONObject("coordinate");
				
				String displayName = currentRestaurant.getString("name");
				String id = currentRestaurant.getString("id");
	     		LatLong latLong = new LatLong(coordinates.getDouble("latitude"), coordinates.getDouble("longitude"));
				String description = currentRestaurant.getJSONObject("location").getJSONArray("address").getString(0);
				String address = currentRestaurant.getJSONObject("location").getJSONArray("address").getString(0);
				double rating = currentRestaurant.getDouble("rating");
				int reviews = currentRestaurant.getInt("review_count"); 
				String url = currentRestaurant.getString("mobile_url");
				String category = currentRestaurant.getJSONArray("categories").getJSONArray(0).getString(0);
				
				tempFoodService = new FoodService(id, displayName);
				tempFoodService.setLatLong(latLong);
				tempFoodService.setDescription(description);
				tempFoodService.setAddress(address);
				tempFoodService.setRating(rating);
				tempFoodService.setReviewCount(reviews);
				tempFoodService.setUrl(url);
				tempFoodService.setCategory(category);
				
				foodServices.add(tempFoodService);
			
			}
			
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			return foodServices;

	}

}
